package org.dallasrowing.model.dao.sqlmap;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dallasrowing.model.Boat;
import org.dallasrowing.model.dao.BoatsDAO;
import org.dallasrowing.model.dao.DAOException;

import com.ibatis.sqlmap.client.SqlMapClient;

@SuppressWarnings( "unchecked" )
public class SqlMapBoatsDAO implements BoatsDAO {

	private static final String BOATS_BY_ID = "Boats.byId";
	private static final String BOATS_ALL_BOATS = "Boats.allBoats";
	private static final String BOATS_BY_NAME = "Boats.byName";
	private static final String BOAT_INSERT = "Boats.insert";
	private static final String BOAT_UPDATE = "Boats.update";
	private SqlMapClient sqlMap;

	public SqlMapBoatsDAO(SqlMapClient sqlMap) {
		this.sqlMap = sqlMap;
	}

	public List<Boat> allBoats(boolean withRetired) throws DAOException {
		try {
			List result = sqlMap.queryForList( BOATS_ALL_BOATS );
			if (! withRetired)
				result = filterRetired(result);
			return result;
		} catch (SQLException e) {
			throw new DAOException(BOATS_ALL_BOATS, e );
		}
	}

	private List<Boat> filterRetired(List<Boat> result) {
		ArrayList<Boat> filtered = new ArrayList<Boat>();
		for (Boat b : result)
		{
			if (!b.isRetired())
				filtered.add(b);
		}
		return filtered;
	}

	public Boat findBoatById(int id) throws DAOException {
		try {
			return (Boat) sqlMap.queryForObject( BOATS_BY_ID, id );
		} catch (SQLException e) {
			throw new DAOException (e);
		}
	}

	public List<Boat> findBoatsWithName(String boatName) throws DAOException {
		try {
			return sqlMap.queryForList( BOATS_BY_NAME, boatName );
		} catch (SQLException e) {
			throw new DAOException(BOATS_ALL_BOATS, e );
		}
	}

	public void createNewBoat(Boat newBoat) throws DAOException {
		try
		{
			sqlMap.insert(BOAT_INSERT, newBoat);
		}
		catch (SQLException e)
		{
			throw new DAOException(BOAT_INSERT, e);
		}
		
	}

	public void updateBoat(Boat boat) throws DAOException {
		try
		{
			sqlMap.update(BOAT_UPDATE, boat);
		}
		catch (SQLException e)
		{
			throw new DAOException(BOAT_UPDATE, e);
		}
	}

}
